package tech.aistar.interceptor;

import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import tech.aistar.pojo.User;
import tech.aistar.util.JWTUtils;
import tech.aistar.vo.Result;

import java.io.PrintWriter;

public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //ajax请求,将本地存储中的token放入到headers中
        String token = request.getHeader("token");
        //判断token的合法性
        if(null!=token && !token.equals("null")){
            //解析token
            Claims claims = JWTUtils.checkJWT(token);
            //如果token对应的字符串是非法的或者已经过期了  claims都是null
            if(claims!=null) {
                //登录是有效的
                Integer uid = claims.get("uid", Integer.class);
                String username = claims.get("username", String.class);

                //request.setAttribute("userId",id);

                User user = new User();
                user.setUId(uid);
                user.setUsername(username);

                request.setAttribute("currUser",user);

                return true;
            }

        }else{
            response.setContentType("application/json;charset=utf-8");
            PrintWriter out = response.getWriter();

            out.print(JSON.toJSONString(new Result("500","请先登录!")));
            return false;
        }
        return false;
    }
}
